<?php
class LoginController
	extends MyApplicationController
{
	public function start()
	{
		parent::start();
		if(ClaycodeLogin::get()->isLogged() == false){
			$this->getLoginForm();
			$this->registry->template->show('Login.php');
		}else{
			header('location:'. fw_util_getAbsoluteUrl());
		}
	}
	
	private function getLoginForm()
	{
		$o_loginForm = new ClaycodeForm('login-form');
		$this->registry->template->s_mainAppDisplay = $o_loginForm->getFormHtml();
	}
	
	public function doLogOut()
	{
		ClaycodeLogin::get()->doLogout();
		header('location:'. fw_util_getAbsoluteUrl());
	}
	
	public function handleLoginFormSubmit()
	{
		if(ClaycodeLogin::get()->isLogged() == false){
			$o_loginForm = new ClaycodeForm('login-form');
			$o_loginForm->validateForm();
			if(count($o_loginForm->getFormErrors()) == 0){
				$arr_postVals = $o_loginForm->getInputValues();
				$user = $this->o_em->getRepository('User')->findOneBy(array(
					'userName' => $arr_postVals['username'], 
					'userPass'=> $arr_postVals['user-password']
				));
				if(isset($user)){
					$s_encryptedUserId = EncryptionHandler::get()->doEncrypt($user->getId());
					//do login
					ClaycodeLogin::get()->doLogin($s_encryptedUserId);
					header('location:'. fw_util_getAbsoluteUrl());
				}else{
					//failed login
					//set an error to the form that the login failed
					$o_loginForm = new ClaycodeForm('login-form');
					$this->registry->template->s_failedMessage = 'login failed';
				}
			}
			$this->registry->template->s_mainAppDisplay = $o_loginForm->getFormHtml();
			$this->registry->template->show('Login.php');
		}else{
			header('location:'. fw_util_getAbsoluteUrl());
		}
	}
	
}